from django.shortcuts import render
from django.http import JsonResponse
from django.core.paginator import Paginator

from django.shortcuts import redirect
from django.urls import reverse
from django.db.models import Q
from datetime import datetime
from common.models import Article
import time,json
from django.core import serializers

def index(request,pIndex=1):
    
    mod = Article.objects

    # 获取、判断并封装关keyword键搜索
    kw = request.GET.get("keyword",None)
    if kw:
        # 查询商品名中只要含有关键字的都可以
        list1 = mod.filter(Q(name__contains=kw))
    else:
        list1 = mod.filter()

    # 获取、判断并封装商品状态state搜索条件
    state = request.GET.get('state','')
    if state != '':
        list1 = list1.filter(state=state)

    # 获取、判断并封装商品状态recommend搜索条件
    recommend = request.GET.get('recommend','')
    if recommend != '':
        list1 = list1.filter(recommend=recommend)

    # 获取、判断并封装商品状态typeid搜索条件
    typeid = request.GET.get('typeid','')
    if typeid != '':
        list1 = list1.filter(typeid=typeid)

    #执行分页处理
    pIndex = int(pIndex)
    page = Paginator(list1,12) #以12条每页创建分页对象
    maxpages = page.num_pages #最大页数
    #判断页数是否越界
    if pIndex > maxpages:
        pIndex = maxpages
    if pIndex < 1:
        pIndex = 1
    list2 = page.page(pIndex) #当前页数据
    plist = page.page_range   #页码数列表
    px = pIndex
    plist2 = set()
    plist2.add(px)
    for x in range(1,6):
        if px-x >= 1 and len(plist2) <= 11:
            plist2.add(px-x)
        if px+x <= maxpages and len(plist2) <= 11:
            plist2.add(px+x)

    plist2 = list(plist2)
    plist2.sort()

    res = serializers.serialize("json",list2)
    data = {}
    data["data"] = json.loads(res)
    data["pIndex"] = pIndex
    data["maxpages"] = maxpages

    return JsonResponse(data,safe=False)